const xml2js = require('xml2js')


module.exports = {
  //解析xml
  ParseXML: (xml) => {
    return new Promise((resolve, reject) => {
      xml2js.parseString(xml, { trim: true }, (err, obj) => {
        if (err) return reject(err)
        return resolve(obj)
      })
    })
  },
  //把数组转为对象
  FormatMessage: (result) => {
    let message = {}
    if (typeof result === 'object') {
      for (let key in result) {
        if (!(result[key] instanceof Array) || result[key].length === 0) {
          continue
        }
        if (result[key].length === 1) {
          let val = result[key][0]
          if (typeof val === 'object') {
            message[key] = formatMessage(val)
          } else {
            message[key] = (val || '').trim()
          }
        } else {
          message[key] = result[key].map(function (item) {
            return formatMessage(item)
          })
        }
      }
    }
    return message
  },

  // 返回文本
  ToText: (message) => {
    return {
      toUserName: message.FromUserName,
      fromUserName: message.ToUserName,
      createTime: new Date().getTime(),
      msgType: 'text',
      content: message.Content
    }
  },

  // 回复模板
  async messageTpl () {
    return '<xml>' +
      '<ToUserName><![CDATA[<%-toUserName%>]]></ToUserName>' +
      '<FromUserName><![CDATA[<%-fromUserName%>]]></FromUserName>' +
      '<CreateTime><%=createTime%></CreateTime>' +
      '<MsgType><![CDATA[<%=msgType%>]]></MsgType>' +
      '<Content><![CDATA[<%-content%>]]></Content>' +
      '</xml>';
  }
}